package com.boarsoft.concurrent;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class SimpleThreadFactory implements ThreadFactory {
	private final ThreadGroup group;
	private static final AtomicInteger poolNumber = new AtomicInteger(1);
	private final AtomicInteger threadNumber = new AtomicInteger(1);
	private final String prefix;
	private final String format;

	private SimpleThreadFactory() {
		SecurityManager s = System.getSecurityManager();
		this.group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
		this.format = "%s-p%dt";
		this.prefix = String.format(format, "threadpool", poolNumber.getAndIncrement());
	}

	private SimpleThreadFactory(String prefix) {
		SecurityManager s = System.getSecurityManager();
		this.group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
		this.format = "%s-p%dt";
		this.prefix = String.format(format, prefix, poolNumber.getAndIncrement());
	}

	private SimpleThreadFactory(String prefix, String format) {
		SecurityManager s = System.getSecurityManager();
		this.group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
		this.format = format;
		this.prefix = String.format(format, prefix, poolNumber.getAndIncrement());
	}

	public Thread newThread(Runnable r) {
		Thread t = new Thread(group, r, prefix + threadNumber.getAndIncrement(), 0);
		if (t.isDaemon()) {
			t.setDaemon(false);
		}
		if (t.getPriority() != Thread.NORM_PRIORITY) {
			t.setPriority(Thread.NORM_PRIORITY);
		}
		return t;
	}
}